<template>
  <div class="create-ad-container">
    <el-page-header @back="$router.go(-1)" content="创建广告" />
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input
            v-model="formData.title"
            placeholder="请输入广告标题"
            clearable
          />
        </el-form-item>

        <el-form-item label="广告类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择广告类型">
            <el-option v-for="(label, value) in typeOptions" :key="value" :label="label" :value="Number(value)" />
          </el-select>
        </el-form-item>

        <el-form-item label="广告素材" prop="advertising">
          <el-upload
            class="ad-image-uploader"
            :action="`http://127.0.0.1:8080/common/upload`"
            :headers="uploadHeaders"
            :data="{ path: 'bishe' }"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :accept="formData.type === 3 ? 'video/mp4,video/x-ms-wmv' : 'image/jpeg,image/png'"
          >
            <!-- 根据类型显示不同的预览 -->
            <template v-if="formData.advertising">
              <!-- 如果是视频广告 -->
              <video 
                v-if="formData.type === 3" 
                class="ad-video" 
                :src="formData.advertising" 
                controls
              ></video>
              <!-- 如果是图片广告 -->
              <img 
                v-else 
                :src="formData.advertising" 
                class="ad-image" 
              />
            </template>
            <el-icon v-else class="ad-image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            {{ 
              formData.type === 3 
              ? '支持mp4/wmv视频文件，最大10MB' 
              : '支持jpg/png图片文件，最大2MB' 
            }}
          </div>
        </el-form-item>
        
        <!-- 如果是视频广告，添加缩略图显示 -->
        <el-form-item v-if="formData.type === 3 && formData.advertising" label="视频缩略图">
          <div class="thumbnail-preview">
            <img 
              :src="`${formData.advertising}?x-oss-process=video/snapshot,t_1000,f_jpg,w_178,h_178,m_fast`" 
              class="ad-image" 
            />
            <div class="upload-tip">视频第一秒自动截取的缩略图</div>
          </div>
        </el-form-item>

        <el-form-item label="广告内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="5"
            placeholder="请输入广告内容"
          />
        </el-form-item>

        <el-form-item label="投放时间" prop="dateRange">
          <el-date-picker
            v-model="formData.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </el-form-item>

        <el-form-item label="预算金额" prop="budget">
          <el-input-number
            v-model="formData.budget"
            :min="0.01"
            :precision="2"
            :step="100"
            controls-position="right"
          />
          <span class="budget-unit">元</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">立即创建</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { createAdvertisement } from '@/api/advertisement'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const formRef = ref(null)
const defaultTime = [new Date(2000, 1, 1, 9, 0, 0), new Date(2000, 1, 1, 18, 0, 0)]

// 广告类型选项
const typeOptions = {
  1: '文字广告',
  2: '图片广告',
  3: '视频广告',
}

// 上传头信息
const uploadHeaders = {
  Authorization: `Bearer ${useUserStore().token}`
}

const formData = reactive({
  title: '',
  content: '',
  dateRange: [],
  budget: 0.01,
  type: 1,
  advertising: ''
})

// 监听广告类型变化，当类型改变时清空已上传的素材
watch(() => formData.type, (newVal, oldVal) => {
  if (newVal !== oldVal && formData.advertising) {
    formData.advertising = ''
    ElMessage.info('已更换广告类型，请重新上传广告素材')
  }
})

const rules = reactive({
  title: [
    { required: true, message: '请输入广告标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择广告类型', trigger: 'change' }
  ],
  advertising: [
    { required: false, message: '请上传广告素材', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入广告内容', trigger: 'blur' },
    { min: 10, message: '至少输入10个字符', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择投放时间', trigger: 'change' }
  ],
  budget: [
    { required: true, message: '请输入预算金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
})

// 上传前验证
const beforeUpload = (file) => {
  // 如果是视频广告
  if (formData.type === 3) {
    const isMP4 = file.type === 'video/mp4'
    const isWMV = file.type === 'video/x-ms-wmv'
    const isLt10M = file.size / 1024 / 1024 < 10
    
    if (!isMP4 && !isWMV) {
      ElMessage.error('上传视频只能是MP4或WMV格式!')
      return false
    }
    if (!isLt10M) {
      ElMessage.error('上传视频大小不能超过10MB!')
      return false
    }
    return true
  } 
  // 如果是图片广告
  else {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG && !isPNG) {
      ElMessage.error('上传图片只能是JPG或PNG格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过2MB!')
      return false
    }
    return true
  }
}

// 素材上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    formData.advertising = res.data
    // 如果是视频广告，提示缩略图自动生成
    if (formData.type === 3) {
      ElMessage.success('视频上传成功，缩略图已自动生成')
    }
  } else {
    ElMessage.error('素材上传失败')
  }
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    const params = {
      title: formData.title,
      content: formData.content,
      startTime: formData.dateRange[0],
      endTime: formData.dateRange[1],
      budget: formData.budget,
      type: formData.type,
      advertising: formData.advertising
    }

    const res = await createAdvertisement(params)
    if (res.data.code === 200) {
      ElMessage.success('创建成功')
      router.push('/advertiser/ads')
    } else {
      ElMessage.error(res.data.message || '创建失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.response?.data?.message || '请求失败')
  }
}
</script>

<style scoped>
.create-ad-container {
  padding: 20px;
}

.form-card {
  margin-top: 20px;
  max-width: 800px;
  margin: 20px auto;
}

.budget-unit {
  margin-left: 10px;
  color: #666;
}

.el-date-editor {
  width: 100%;
}

.el-input-number {
  width: 200px;
}

.ad-image-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.ad-image-uploader:hover {
  border-color: #409EFF;
}

.ad-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.ad-image, .ad-video {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.ad-video {
  object-fit: contain;
  background-color: #000;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

.thumbnail-preview {
  display: inline-block;
}
</style>